import axios from 'axios'
import { getToken, isLogin, deleteToken} from '@u';
import { message } from 'antd';
import { createBrowserHistory} from 'history'

const history = createBrowserHistory()
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
axios.defaults.timeout = 8000;
//const getToken = () => localStorage.getItem('token');
// 添加拦截器
axios.interceptors.request.use(function (config) {
  //设置全局的loging
  message.loading({
    content: '正在加载'
  })
  // 请求头中添加token
  if (getToken()) {
    config.headers.token = getToken();
  }
  return config;
}, function (error) {

  return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (res) {
  // 判断登录状态
  switch (res.data.code) {
    case 401: // 登录状态过期
   
    message.error({
      content: '用户登录状态过期',
      duration: 2,
      onClose: () => {
        deleteToken()
        history.replace('/login')
        history.go(0)
      }
    })
      break;
    case 403: // 未登录
    message.error({
      content: '用户未登录',
      duration: 2,
      onClose: () => {
        history.replace('/login')
        history.go(0)
      }
    })
      break;

    default:
      break;
  }
  return res;
}, function (error) {

//清楚全局的loging
message.destroy()


  return Promise.reject(error);
});

export default axios;